import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { nodePolyfills } from 'vite-plugin-node-polyfills'

export default defineConfig({
  plugins: [
    vue(),
    // nodePolyfills
    nodePolyfills({
      include: ['stream', 'http', 'https', 'crypto', 'util'],
      globals: {
        Buffer: true,
        process: true,
      }
    })
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    },
    extensions: ['.vue', '.ts', '.js', '.json'],
    mainFields: ['module', 'main', 'browser']
  },
  esbuild: {
    target: ['es2020', 'edge88', 'firefox78', 'chrome87']
  },
  server: {
    open: true,
    port: 3002,
    host: '0.0.0.0',
    hmr: {
      overlay: true
    }
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks: (filePath) => {
          if (filePath.includes('node_modules')) {
            const moduleName = filePath.toString().split('node_modules/')[1].split('/')[0].toString()

            // 将关键模块合并到同一个 chunk
            if (moduleName === 'vant' ||
              moduleName === 'axios' ||
              moduleName === 'follow-redirects') {
              return 'vendor-core'
            }

            return moduleName
          }
        }
      },
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        quietDeps: true,
      }
    }
  },
  // 添加全局变量定义
  define: {
    'process.env': {},
    'process.browser': true,
    'process.version': JSON.stringify('v16.0.0')
  }
})